package com.app.couponsharelife.ui.main.me.withdrawal

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.hwangjr.rxbus.RxBus
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.AlipayInfoBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.main.me.bindalipay.BindAlipayActivity
import com.app.couponsharelife.ui.viewmodel.MeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_withdrawal.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*
import java.math.BigDecimal
import java.util.HashMap

class WithdrawalActivity : BaseActivity() {
    private var temp: CharSequence? = null    // 监听前的文本
    private var editStart: Int = 0      // 光标开始位置
    private var editEnd: Int = 0        // 光标结束位置
    override val viewLayoutId: Int get() = R.layout.activity_withdrawal

    private var alipay: AlipayInfoBean? = null

    /**
     * 是否需要重新请求支付宝信息
     */
    private var isNeedData = false

    private var mViewModel: MeViewModel? = null

    private var isWithdrawSuccess = false

    override fun initViews() {
        if (intent.getSerializableExtra("alipay") != null) {
            alipay = intent.getSerializableExtra("alipay") as AlipayInfoBean
            tvCanWithdrawalNum.text = String.format("¥%s元", alipay!!.balance)
            etName.setText(alipay!!.name)
            etName.setSelection(alipay!!.name.length)
            etAlipayAccount.setText(alipay!!.aliPayAccount)
        } else {
            isNeedData = true
        }
        initToolBar()
        initEditText()
        tvSendApplicationbtn.setOnClickListener {
            addWithdrawApply()
        }
        etWithdrawalNum.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(s: Editable) {
                editStart = etWithdrawalNum.selectionStart
                editEnd = etWithdrawalNum.selectionEnd
                val arr = temp.toString().split("[.]".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                if (arr.size > 1) {
                    if (arr[1].length > 2) {
                        s.delete(editStart - 1, editEnd)
                        val tempSelection = editStart
                        etWithdrawalNum.text=s
                        etWithdrawalNum.setSelection(tempSelection)
                    }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                temp=s
            }
        })
    }

    private fun initEditText() {
        watchEditText(etName, null)
        watchEditText(etAlipayAccount, null)
        watchEditText(etWithdrawalNum, null)
    }

    private fun initToolBar() {
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "提现"
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.getAlipayInfo()!!.hasObservers()) {
            mViewModel!!.getAlipayInfo()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetAlipayInfo(hashMapOf(), false)
                        if (it.error!!.message == "账户不存在") {
                            val intent = Intent(this, BindAlipayActivity::class.java)
                            intent.putExtra("isWithdraw", true)
                            startActivity(intent)
                            finish()
                        } else
                            showToastMsg(parseErrorDate(it.error.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetAlipayInfo(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetAlipayInfo(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            if (it.data.data!!.aliPayAccount != "") {
                                alipay = it.data.data
                                tvCanWithdrawalNum.text = String.format("¥%s元", alipay!!.balance)
                                etName.setText(alipay!!.name)
                                etName.setSelection(alipay!!.name.length)
                                etAlipayAccount.setText(alipay!!.aliPayAccount)
                            } else {
                                val intent = Intent(this, BindAlipayActivity::class.java)
                                intent.putExtra("isWithdraw", true)
                                startActivity(intent)
                                finish()
                            }
                        } else {
                            showToastMsg("获取失败")
                        }
                    }
                }
            })
            mViewModel!!.addWithdrawApply()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddWithdrawApply(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddWithdrawApply(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshAddWithdrawApply(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            getAlipayInfo()
                            etWithdrawalNum.setText("")
                            showToastMsg("提交成功，等待审核")
                            isWithdrawSuccess = true
                        } else {
                            dismissProgressDialog()
                            showToastMsg("申请失败")
                        }
                    }
                }
            })
        }
        if (isNeedData)
            getAlipayInfo()
    }

    private fun getAlipayInfo() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.freshGetAlipayInfo(map, true)
    }

    private fun addWithdrawApply() {
        if (TextUtils.isEmpty(etName.text)) {
            showToastMsg("请输入真实姓名")
            return
        } else {
            if (etName.text.toString() != alipay!!.name) {
                showToastMsg("真实姓名不匹配")
                return
            }
        }
        if (TextUtils.isEmpty(etAlipayAccount.text)) {
            showToastMsg("请输入支付宝账号")
            return
        } else {
            if (etAlipayAccount.text.toString() != alipay!!.aliPayAccount) {
                showToastMsg("支付宝账号不匹配")
                return
            }
        }
        if (TextUtils.isEmpty(etWithdrawalNum.text)) {
            showToastMsg("请输入提现金额")
            return
        }
        if (BigDecimal(etWithdrawalNum.text.toString()) < BigDecimal("2")) {
            showToastMsg("提现金额最低2元")
            return
        }
        if (BigDecimal(alipay!!.balance).subtract(BigDecimal(etWithdrawalNum.text.toString())) < BigDecimal.ZERO) {
            showToastMsg("提现金额不能大于可提现金额")
            return
        }
        val map = HashMap<String, String>()
        map["money"] = BigDecimal(etWithdrawalNum.text.toString()).toString()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshAddWithdrawApply(map, true)
    }

    private fun watchEditText(editText: EditText, imageView: ImageView?) {
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(s)) {
                    imageView?.visibility = View.INVISIBLE
                    imageView?.isClickable = false
                } else {
                    imageView?.visibility = View.VISIBLE
                    imageView?.isClickable = true
                }
                checkTotalEdit()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    private fun checkTotalEdit() {
        if (!TextUtils.isEmpty(etName.text) &&
                !TextUtils.isEmpty(etAlipayAccount.text) &&
                !TextUtils.isEmpty(etWithdrawalNum.text) &&
                BigDecimal(alipay!!.balance).subtract(BigDecimal(etWithdrawalNum.text.toString())) > BigDecimal.ZERO) {
            tvSendApplicationbtn.setBackgroundResource(R.drawable.btn_bg1)
        } else {
            tvSendApplicationbtn.setBackgroundResource(R.drawable.btn_bg2)
        }
    }

    override fun onBackPressed() {
        if (isWithdrawSuccess) {
            RxBus.get().post("freshBalance", "")
        }
        super.onBackPressed()
    }
}
